import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:openim_common/openim_common.dart';

class ImageSelectionDialog extends StatefulWidget {
  final List<XFile> selectedImages;
  final Function(List<XFile> confirmedImages)? onConfirm;
  final Function()? onCancel;

  const ImageSelectionDialog({
    Key? key,
    required this.selectedImages,
    this.onConfirm,
    this.onCancel,
  }) : super(key: key);

  @override
  State<ImageSelectionDialog> createState() => _ImageSelectionDialogState();
}

class _ImageSelectionDialogState extends State<ImageSelectionDialog> {
  late List<XFile> _images;
  final Set<int> _selectedIndices = <int>{};
  bool _isUploading = false;

  @override
  void initState() {
    super.initState();
    _images = List.from(widget.selectedImages);
    // 默认全选
    for (int i = 0; i < _images.length; i++) {
      _selectedIndices.add(i);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.transparent,
      child: Center(
        child: Container(
          width: 350.w,
          height: 500.h,
          margin: EdgeInsets.symmetric(horizontal: 20.w),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(16.r),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.1),
                blurRadius: 20,
                offset: const Offset(0, 8),
              ),
            ],
          ),
          child: Column(
            children: [
              // 标题栏
              Container(
                padding: EdgeInsets.all(16.w),
                decoration: BoxDecoration(
                  border: Border(
                    bottom: BorderSide(
                      color: Styles.c_E8EAEF,
                      width: 1,
                    ),
                  ),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      '选择图片',
                      style: Styles.ts_0C1C33_17sp.copyWith(
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    Text(
                      '已选择 ${_selectedIndices.length}/${_images.length}',
                      style: Styles.ts_8E9AB0_14sp,
                    ),
                  ],
                ),
              ),
              
              // 图片网格
              Expanded(
                child: Container(
                  padding: EdgeInsets.all(16.w),
                  child: GridView.builder(
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 3,
                      crossAxisSpacing: 8.w,
                      mainAxisSpacing: 8.w,
                      childAspectRatio: 1.0,
                    ),
                    itemCount: _images.length,
                    itemBuilder: (context, index) {
                      final isSelected = _selectedIndices.contains(index);
                      return GestureDetector(
                        onTap: () => _toggleSelection(index),
                        child: Container(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(8.r),
                            border: Border.all(
                              color: isSelected ? Styles.c_0089FF : Colors.transparent,
                              width: 2,
                            ),
                          ),
                          child: Stack(
                            children: [
                              // 图片
                              ClipRRect(
                                borderRadius: BorderRadius.circular(6.r),
                                child: Image.file(
                                  File(_images[index].path),
                                  width: double.infinity,
                                  height: double.infinity,
                                  fit: BoxFit.cover,
                                  errorBuilder: (context, error, stackTrace) {
                                    return Container(
                                      color: Styles.c_F0F2F6,
                                      child: Icon(
                                        Icons.broken_image,
                                        color: Styles.c_8E9AB0,
                                        size: 24.w,
                                      ),
                                    );
                                  },
                                ),
                              ),
                              
                              // 选择状态覆盖层
                              if (isSelected)
                                Container(
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(6.r),
                                    color: Styles.c_0089FF.withOpacity(0.3),
                                  ),
                                ),
                              
                              // 选择图标
                              Positioned(
                                top: 4.w,
                                right: 4.w,
                                child: Container(
                                  width: 20.w,
                                  height: 20.w,
                                  decoration: BoxDecoration(
                                    color: isSelected ? Styles.c_0089FF : Colors.white.withOpacity(0.8),
                                    shape: BoxShape.circle,
                                    border: Border.all(
                                      color: isSelected ? Styles.c_0089FF : Styles.c_8E9AB0,
                                      width: 1,
                                    ),
                                  ),
                                  child: isSelected
                                      ? Icon(
                                          Icons.check,
                                          color: Colors.white,
                                          size: 12.w,
                                        )
                                      : null,
                                ),
                              ),
                            ],
                          ),
                        ),
                      );
                    },
                  ),
                ),
              ),
              
              // 底部按钮
              Container(
                padding: EdgeInsets.all(16.w),
                decoration: BoxDecoration(
                  border: Border(
                    top: BorderSide(
                      color: Styles.c_E8EAEF,
                      width: 1,
                    ),
                  ),
                ),
                child: Row(
                  children: [
                    // 全选/取消全选按钮
                    TextButton(
                      onPressed: _toggleSelectAll,
                      child: Text(
                        _selectedIndices.length == _images.length ? '取消全选' : '全选',
                        style: Styles.ts_0089FF_14sp,
                      ),
                    ),
                    
                    const Spacer(),
                    
                    // 取消按钮
                    TextButton(
                      onPressed: _isUploading ? null : () {
                        widget.onCancel?.call();
                        Get.back();
                      },
                      child: Text(
                        '取消',
                        style: Styles.ts_8E9AB0_14sp,
                      ),
                    ),
                    
                    8.horizontalSpace,
                    
                    // 确认上传按钮
                    ElevatedButton(
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Styles.c_0089FF,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8.r),
                        ),
                        padding: EdgeInsets.symmetric(
                          horizontal: 20.w,
                          vertical: 10.h,
                        ),
                      ),
                      onPressed: _selectedIndices.isEmpty || _isUploading
                          ? null
                          : _confirmUpload,
                      child: _isUploading
                          ? SizedBox(
                              width: 16.w,
                              height: 16.w,
                              child: CircularProgressIndicator(
                                strokeWidth: 2,
                                color: Colors.white,
                              ),
                            )
                          : Text(
                              '确认上传 (${_selectedIndices.length})',
                              style: Styles.ts_FFFFFF_14sp,
                            ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _toggleSelection(int index) {
    setState(() {
      if (_selectedIndices.contains(index)) {
        _selectedIndices.remove(index);
      } else {
        _selectedIndices.add(index);
      }
    });
  }

  void _toggleSelectAll() {
    setState(() {
      if (_selectedIndices.length == _images.length) {
        _selectedIndices.clear();
      } else {
        _selectedIndices.clear();
        for (int i = 0; i < _images.length; i++) {
          _selectedIndices.add(i);
        }
      }
    });
  }

  void _confirmUpload() async {
    if (_selectedIndices.isEmpty) return;

    setState(() {
      _isUploading = true;
    });

    try {
      // 获取选中的图片
      final selectedImages = _selectedIndices
          .map((index) => _images[index])
          .toList();

      // 调用确认回调
      widget.onConfirm?.call(selectedImages);
      
      // 关闭对话框
      Get.back(result: selectedImages);
    } catch (e) {
      IMViews.showToast('上传失败: $e');
    } finally {
      setState(() {
        _isUploading = false;
      });
    }
  }
}

// 静态方法用于显示对话框
class ImageSelectionDialogHelper {
  static Future<List<XFile>?> show({
    required List<XFile> selectedImages,
    Function(List<XFile> confirmedImages)? onConfirm,
  }) async {
    return await Get.dialog<List<XFile>>(
      ImageSelectionDialog(
        selectedImages: selectedImages,
        onConfirm: onConfirm,
      ),
      barrierDismissible: false,
    );
  }
}